import axios from "axios";
import { message } from "ant-design-vue";
import router from "@/router";
import { useWebStore } from "@/store";

const webStore = useWebStore();

const baseUrl = import.meta.env.VITE_APP_BASE_API;
// create an axios instance
const service = axios.create({
  baseURL: baseUrl,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) config.headers["X-exam-Token"] = token ?? "";
    return config;
  },
  (error) => {
    // do something with request error
    // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    if (response.data.code === 200) {
      // 服务端定义的响应code码为0时请求成功
      // 使用Promise.resolve 正常响应
      return Promise.resolve(response.data);
    } else {
      if (response.config.responseType === "blob") {
        return Promise.resolve(response.data);
      }
      switch (response.data.code) {
        case 401:
          router.push("/login");
          break;
        default:
          message.error(response.data.message);
      }
      return Promise.reject(new Error(response.data.message || "Error"));
    }
  },
  (error) => {
    if (error.response.data.code === 401) {
      webStore.setLastVisitRoute({ lastVisitRoute: router.currentRoute.value.fullPath });
      router.push("/login");
    }
    return Promise.reject(error);
  }
);

export default service;
